﻿@using KC.Framework.Tenant
@using KC.Web.Admin.Constants
@using KC.MVC.Core.Constants
@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService AuthorizationService
@{
    ViewBag.Title = "数据库管理";
    Layout = "~/Views/Shared/_ListLayout.cshtml";
}

<div id="toolbar">
    <div>
        @*数据库池管理-保存数据库连接*@
        @if ((await AuthorizationService.AuthorizeAsync(User, "13914A9C-49AB-4001-BA3B-C1C1D66969CB")).Succeeded)
        {
            <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="fa fa-plus" onclick="addDatabasePool()">添加</a>
        }
        @*数据库池管理-保存数据库连接*@
        @if ((await AuthorizationService.AuthorizeAsync(User, "13914A9C-49AB-4001-BA3B-C1C1D66969CB")).Succeeded)
        {
            <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="fa fa-pencil" onclick="editDatabasePool()">编辑</a>
        }
        @*数据库池管理-删除数据库*@
        @if ((await AuthorizationService.AuthorizeAsync(User, "F6169808-FC59-49FD-99C5-9B98FF99F7E4")).Succeeded)
        {
            <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="fa fa-trash" onclick="removeDatabasePool()">删除</a>
        }

    </div>

    <div>
        <div id="divSearchMenu" class="easyui-menu" style="width:120px">
            <div data-options="name:'Server',selected:true">服务器</div>
            <div data-options="name:'Database'">数据库</div>
            <div data-options="name:'Username'">用户名</div>
        </div>
        <input id="txtSearchbox" class="easyui-searchbox" style="width: 300px; height: 26px;" />
        <a href="javascript:void(0)" onclick="RefreshSearch()" class="easyui-linkbutton" data-options="iconCls:'fa fa-refresh'">刷新</a>
    </div>
</div>
<table id="datagrid" title=""></table>

@section scripts
    {
    <script type="text/javascript" src="@(KC.Framework.Base.GlobalConfig.ResWebDomain)lib/jquery-easyui/datagrid-detailview.js"></script>
    <script type="text/javascript">
        $(function() {
            InitDataGrid();
        });

        var loadDataUrl = '@Url.Action(ActionName.DatabasePool.LoadDatabasePoolList, ControllerName.DatabasePool)';
        var LoadTenantUserListByDatabasePoolUrl = '@Url.Action(ActionName.DatabasePool.LoadTenantUserListByDatabasePool, ControllerName.DatabasePool)';
        var tenantDetailUrl = '@Url.Action(ActionName.Tenant.TenantDetail, ControllerName.Tenant)';
        function InitDataGrid() {
            var $dataGrid = $('#datagrid').datagrid({
                view: detailview,
                url: loadDataUrl,
                method: 'get',
                idField: 'DatabasePoolId',
                striped: true,
                fitColumns: true,
                rownumbers: true,
                singleSelect: true,
                pagination: true,
                nowrap: false,
                fit: true,
                pageSize: 10,
                pageList: [10, 20, 50, 100],
                showFooter: false,
                toolbar: "#toolbar",
                //toolbar: [{ text: document.getElementById('toolbar') }],
                columns: [[
                        { field: 'DatabasePoolId', title: 'Id', width: 30, align: 'left' },
                        { field: 'CloudTypeString', title: '云服务', width: 50, align: 'left' },
                        { field: 'DatabaseTypeString', title: '类型', width: 80, align: 'left' },
                        { field: 'Server', title: '服务器', width: 200, align: 'left' },
                        { field: 'Database', title: '数据库', width: 100, align: 'left' },
                        { field: 'UserName', title: '用户名', width: 100, align: 'left' },
                        //{ field: 'CreatedBy', title: '创建人', width: 100, align: 'left' },
                        //{ field: 'CreatedDate', title: '创建时间', formatter: Common.DateFormatter, width: 100, align: 'left' },
                        { field: 'PasswordExpiredTime', title: '密码过期时间', formatter: Common.DateFormatter, width: 100, align: 'left' },
                        { field: 'TenantCount', title: '租户个数', width: 50, align: 'left', editor: { type: 'numberbox', options: { min: 20, precision: 0 } } }
                    ]
                ],
                onBeforeLoad: function(param) {
                    /*var bId = $("#txtBId").val();
                var AllSearchKey = $("#txtAllSearchKey").val();
                param.bId = bId;
                param.AllSearchKey = AllSearchKey;*/
                },
                onLoadSuccess: function(data) {
                },
                onLoadError: function() {
                },
                detailFormatter: function (index,row) {
                    return '<div style="padding:2px"><table class="ddv"></table></div>';
                },
                onExpandRow: function (index, row) {
                    var ddv = $(this).datagrid('getRowDetail', index).find('table.ddv');
                    ddv.datagrid({
                        url: LoadTenantUserListByDatabasePoolUrl + '?DatabasePoolId=' + row.DatabasePoolId,
                        fitColumns: true,
                        singleSelect: true,
                        rownumbers: true,
                        loadMsg: '',
                        height: 'auto',
                        columns: [[
                            { field: 'TenantName', title: '租户代码', width: 100, align: 'left' },
                            { field: 'TenantDisplayName', title: '租户名', width: 80, align: 'left',
                                formatter: function (value, row, index) {
                                    return '<a href="javascript:void(0);" onclick="MainPage_PostMessage(\'openPage\', \'' + tenantDetailUrl + '\', \'id=' + row.TenantId + '\')" style="text-decoration: none; color: #0000ff">' + value + '</a>';
                                }
                            },
                            { field: 'CloudTypeString', title: '云服务', width: 60, align: 'left' },
                            { field: 'VersionString', title: '版本类型', width: 40, align: 'left' },
                            { field: 'TenantTypeString', title: '店铺类型', width: 50, align: 'left' },
                            { field: 'NickName', title: 'NickName', width: 50, align: 'center' }
                        ]],
                        onResize: function () {
                            $('#datagrid').datagrid('fixDetailRowHeight', index);
                        },
                        onLoadSuccess: function () {
                            setTimeout(function () {
                                $('#datagrid').datagrid('fixDetailRowHeight', index);
                            }, 0);
                        }
                    });
                }
            });

            $('#txtSearchbox').searchbox({
                menu: '#divSearchMenu',
                prompt: '请输入查询值',
                searcher: searchData
            });
        }

        var getFormUrl = '@Url.Action(ActionName.DatabasePool.GetDatabasePoolForm, ControllerName.DatabasePool)';
        var saveFormUrl = '@Url.Action(ActionName.DatabasePool.SaveDatabasePoolForm, ControllerName.DatabasePool)';
        function opentForm(id) {
            var dialog = $.easyui.showDialog({
                title: "保存数据",
                width: 420,
                height: 350,
                href: getFormUrl + "?id=" + id,
                modal: true,
                topMost: false,
                enableHeaderContextMenu: false,
                enableApplyButton: false,
                onSave: function (d) {
                    var validate = d.form("enableValidation").form("validate");
                    if (validate) {
                        $.easyui.loading({ msg: '正在保存数据，请稍等...' });
                        $.ajax({
                            async: true,
                            type: "post",
                            dataType: "json",
                            url: saveFormUrl,
                            data: AddAntiForgeryToken(d.form("getData")),
                            success: function(data) {
                                if (data.success) {
                                    d.window('close');
                                    if (data.Result) {
                                        $('#datagrid').datagrid('reload');
                                        $.messager.showInfoCenter('系统提示', '保存数据成功。', 1000);
                                    } else {
                                        $.messager.showErrorCenter('错误消息', '保存数据失败。', 1000);
                                    }
                                } else {
                                    $.messager.showErrorCenter('错误消息', data.message, 1000);
                                }
                            },
                            complete: function() {
                                $.easyui.loaded();
                            }
                        });
                        return false;
                    } else {
                        return false;
                    }
                },
                onLoad: function() {
                    var f = $(this), ret = $.fn.dialog.defaults.onLoad();
                    f.form("disableValidation").form("enableValidation");
                    return ret;
                }
            });
        }

        function RefreshSearch() {

            $("#txtSearchbox").searchbox('setValue', '');
            searchData('', '');
        }

        function searchData(value, name) {
            $('#datagrid').datagrid('unselectAll');
            $('#datagrid').datagrid('load', { "searchKey": name, "searchValue": value });
        }

        function addDatabasePool() {
            opentForm(0);
        }

        function editDatabasePool() {
            var row = $('#datagrid').datagrid('getSelected');
            if (row) {
                opentForm(row.DatabasePoolId);
            } else {
                $.messager.showErrorCenter('系统提示', '请选择需要编辑的数据！', 2000);
            }
        }

        var removeUrl = '@Url.Action(ActionName.DatabasePool.RemoveDatabasePool, ControllerName.DatabasePool)';
        function removeDatabasePool() {
            var row = $('#datagrid').datagrid('getSelected');
            if (row) {
                $.messager.confirm('确认', '是否确定删除该条记录?', function(r) {
                    if (r) {
                        $.easyui.loading({ msg: '正在保存数据，请稍等...' });
                        $.post(removeUrl, { id: row.DatabasePoolId }, function(data) {
                            $.easyui.loaded();
                            if (data.success) {
                                if (data.Result) {
                                    $('#datagrid').datagrid('reload');
                                    $.messager.showInfoCenter('系统提示', '删除数据成功。', 1000);
                                } else {
                                    $.messager.showErrorCenter('错误消息', '删除数据失败。', 1000);
                                }
                            } else {
                                $.data.showErrorCenter('错误消息', data.message, 1000);
                            }
                        }, 'json');
                    }
                });
            } else {
                $.messager.showErrorCenter('系统提示', '请选择需要删除的数据！', 2000);
            }
        }

        var getPasswordHashUrl = '@Url.Action(ActionName.Tenant.GeneratePasswordHash, ControllerName.Tenant)';
        function generatePasswordHash() {
            //debugger;
            var password = $('#UserPassword').val();
            if (password == '') {
                $.messager.showErrorCenter('错误消息', "用户密码不能为空", 1000);
                return;
            }
            $.messager.confirm('确认', '是否根据密码:（' + password + '）进行加密，生成加密后的密码?', function(r) {
                if (r) {
                    $.easyui.loading({ msg: '正在保存数据，请稍等...' });
                    $.post(getPasswordHashUrl, { password: password }, function(result) {
                        $.easyui.loaded();
                        if (result.success) {
                            $('#UserPasswordHash').val(result.message);
                        } else {
                            $.messager.showErrorCenter('错误消息', result.message, 1000);
                        }
                    }, 'json');
                }
            });
        }

        var testConnectionUrl = '@Url.Action(ActionName.DatabasePool.TestDatabaseConnection, ControllerName.DatabasePool)';
        function testConnection() {
            //debugger;
            var cloudType = $('#CloudType').val();
            if (cloudType == '') {
                $.messager.showErrorCenter('错误消息', "云类型不能为空", 1000);
                return;
            }
            var server = $('#Server').val();
            if (server == '') {
                $.messager.showErrorCenter('错误消息', "数据库服务器不能为空", 1000);
                return;
            }
            var database = $('#Database').val();
            if (database == '') {
                $.messager.showErrorCenter('错误消息', "数据库实例不能为空", 1000);
                return;
            }
            var userId = $('#UserName').val();
            if (userId == '') {
                $.messager.showErrorCenter('错误消息', "用户不能为空", 1000);
                return;
            }
            var password = $('#UserPasswordHash').val();
            if (password == '') {
                $.messager.showErrorCenter('错误消息', "用户密码不能为空", 1000);
                return;
            }
            $.easyui.loading({ msg: '正在保存数据，请稍等...' });
            $.post(testConnectionUrl,
                {
                    CloudType: cloudType,
                    Server: server,
                    Database: database,
                    UserName: userId,
                    UserPasswordHash: password,
                },
                function(data) {
                    $.easyui.loaded();
                    if (data.success) {
                        if (data.Result == '') {
                            $.messager.showInfoCenter('系统提示', '测试数据库连接成功。', 1000);
                        } else {
                            $.messager.showErrorCenter('错误消息', data.Result, 3000);
                        }
                    } else {
                        $.messager.showErrorCenter('错误消息', data.message, 1000);
                    }
                }, 'json');
        }
    </script>

    <script>
        var domain = '@ViewBag.CurrentAppDomain';
        function OpenTab(url) {
            MainPage_PostMessage("openPage", domain + url);
        }
        function CloseTab(url) {
            MainPage_PostMessage("closePage", domain + url);
        }
        function RefreshTab(url) {
            MainPage_PostMessage("getPage", domain + url);
        }
        var detailQueryString = 'id=';
        function OpenDetailTab(url, id) {
            detailQueryString = detailQueryString + id;
            MainPage_PostMessage("openPage", domain + url, detailQueryString);
        }

        window.addEventListener('message', function (e) {
            //debugger;
            if (e.data) {
                var rdata = eval('(' + e.data + ')')
                console.log(rdata);

                var command = rdata.command;
                var returnKey = rdata.returnKey;
                var data = rdata.data;
                if (command === 'getPage' && data) {
                    //alert('刷新Iframe(产品管理)的Id：' + data.ID);
                    var frmUrl = window.top.frames[data.id].location.href;
                    if (frmUrl.indexOf("?") > 0) {
                        frmUrl = frmUrl + "&" + detailQueryString;
                    } else {
                        frmUrl = frmUrl + "?" + detailQueryString;
                    }
                    console.log(data.id + ": " + frmUrl);

                    window.top.frames[data.id].location.reload();
                    //window.top.frames[data.id].location.href = frmUrl;
                }
            }
        }, false);
    </script>
}

